import React, { Component } from 'react'
import { NavBar } from "antd-mobile";
import SearchInput from "../searchInput/SearchInput";
import "./Category.scss";
import myaxios from "../../utils/myaxios";
import axios from "axios";
export default class Category extends Component {
  constructor(props) {
    super(props);
    const CancelToken = axios.CancelToken;
    this.source = CancelToken.source();
  }
  state = {
    categories: [],//返回的数据菜单
    select_index: 0,//选中的左边的菜单
    categories_content: [],//右边菜单渲染的内容
  }
  // 左侧分类菜单点击
  handleItemClick = (e) => {
    // 获取点击选中的项
    let select_index = e.target.getAttribute("data-index");
    this.setState({
      select_index: parseInt(select_index),
      categories_content: this.state.categories[select_index].children
    })
  }
  // 右侧图片点击
  handleProductItemClick = (e) => {
    let cid = e.target.getAttribute("data-index");
    this.props.history.push("/goodList?cid=" + cid)
  }
  // 获取分类菜单的数据
  getCatrgories = (params) => {
    myaxios
      .get("categories" ,{
        cancelToken: this.source.token,
      })
      .then((res) => {
        this.setCategories(res)
      })
      .catch((err) => {
        console.log(err);
      })
  }
  // 设置分类菜单的数据
  // is_storaged 代表是否之前已经缓存过
  setCategories = (res, is_storaged) => {
    // 缓存请求的数据
    let categories_cache = {};
    // 如果之前没有缓存过
    if (!is_storaged) {
      // 获取本地缓存
      categories_cache = { date: Date.now(), categories: res };
      // 缓存到本地
      localStorage.setItem("categories_cache", JSON.stringify(categories_cache));
    }
    this.setState({
      categories: res,
      categories_content: res[0].children
    });
  }
  componentDidMount() {
    // 进来的时候 先判断本地缓存是否过期
    // 如果没有过期的情况下 直接获取本地的缓存
    let categories_cache = localStorage.getItem("categories_cache")
    // 如果本地缓存不为空
    if (categories_cache && JSON.parse(categories_cache).date) {
      // 判断本地缓存是否过期
      // 当前时间
      let current_time = Date.now();
      let storage_time = JSON.parse(categories_cache).date;
      if (current_time - storage_time >  60 * 60 * 1000) {
        // 一小时过期
        this.getCatrgories();
      } else {
        // 缓存没有过期，第二个参数代表是否已经过期
        this.setCategories(JSON.parse(categories_cache).categories, true);
      }
    } else {
      this.getCatrgories();
    }
  }
  componentWillUnmount() {
    this.source.cancel('Operation canceled by the user.');
  }
  render() {
    return (
      <div className="yg-category">
        {/* 首页导航条开始 */}
        <div className="yg-category-nav">
          <NavBar className="category-nav-title">优购商城</NavBar>
        </div>
        {/* 首页搜索框开始 */}
        <div className="yg-category-search">
          <SearchInput></SearchInput>
        </div>
        {/* 分类菜单开始 */}
        <div className="yg-category-content">
          <div className="content-left" onClick={this.handleItemClick}>
            {
              this.state.categories.map((v, index) => {
                return (
                  <div data-index={index} className={this.state.select_index === index ? "active content-left-item" : "content-left-item"} key={v.cat_id} >
                    {v.cat_name}
                  </div>
                );
              })
            }
          </div>
          <div className="content-right">
            {
              this.state.categories_content.map((v, i) => {
                return <div className="content-right-item" key={v.cat_id}>
                  {/* 二级菜单标题 */}
                  <div className="right-item-title" key={v.cat_id}>
                    {"/"}{v.cat_name}{"/"}
                  </div>
                  {/* 产品列表 */}
                  <div className="product-list">
                    {
                      v.children && v.children.map(v => {
                        return <div key={v.cat_id} data-index={v.cat_id} className="product-list-item">
                          <div className="imageWrapper">
                            <img src={v.cat_icon} alt="" onClick={this.handleProductItemClick} data-index={v.cat_id} />
                          </div>
                          <div className="item-title">
                            {v.cat_name}
                          </div>
                        </div>
                      })
                    }
                  </div>
                </div>
              })
            }
          </div>
        </div>
      </div>
    )
  }
}
